package cn.yangliu.nacos.comm.handler;

import cn.yangliu.nacos.comm.JsonResult;
import cn.yangliu.nacos.comm.enums.GlobalResultCode;
import org.apache.logging.log4j.util.Strings;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

/**
 * The type of nacos.
 *
 * @author 问道于盲
 * @date 2020 -01-05
 */
public interface ExceptionResolver {

    /**
     * Http status to sae result json result.
     *
     * @param status the status
     * @return the json result
     */
    default JsonResult<Object> httpStatusToSaeResult(HttpStatus status) {
        JsonResult<Object> body = null;
        if (status.equals(HttpStatus.NOT_FOUND)) {
            body = JsonResult.getInstance(GlobalResultCode.INTERFACE_ADDRESS_NOT_FOUND);
        } else if (status.equals(HttpStatus.UNAUTHORIZED)) {
            body = JsonResult.getInstance(GlobalResultCode.UNAUTHORIZED);
        } else if (status.equals(HttpStatus.FORBIDDEN)) {
            body = JsonResult.getInstance(GlobalResultCode.ACCESS_DENIED);
        } else if (status.is4xxClientError()) {
            body = JsonResult.getInstance(GlobalResultCode.BAD_REQUEST);
        } else {
            body = JsonResult.getInstance(GlobalResultCode.SYSTEM_INNER_ERROR);
        }
        return body;
    }


    /**
     * Handle binding result json result.
     *
     * @param result the result
     * @return json result
     */
    default JsonResult<Object> handleBindingResult(BindingResult result) {
        JsonResult<Object> saeResult = JsonResult.getInstance(
                GlobalResultCode.PARAM_TYPE_BIND_ERROR);

        if (!result.hasErrors()) {
            return saeResult;
        }
        /**
         * DefaultMessage in AllErrors list splitting by ','
         */
        saeResult.setMsg(Strings.join(result.getAllErrors().stream()
                .map(ObjectError::getDefaultMessage).iterator(), ','));
        return saeResult;
    }


}
